﻿using PKTools.Database;
using PKTools.Scheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scheduler
{
    class TaskDispatcher : ITaskDispatcher
    {
        public ITask GetWaitingTask(DateTime currentTime)
        {
            using (var sql = new MsSql(true))
            {
                var
                    taskList = sql.LoadBy<JobTask>(e => e.Executing == false && e.EET <= currentTime, 1);

                if (taskList.Count == 0)
                {
                    sql.Commit();
                    return null;
                }

                var
                    task = taskList[0];

                task.Executing = true;

                sql.Update(task);
                sql.Commit();

                return task;
            }
        }
    }
}
